package com.ibeeking.found.id.rest.config.id;

import com.ibeeking.found.common.constants.IdRedisConstant;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.id.Sequence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.annotation.Resource;


@Configuration
public class SnowflakeIdConfig {

    private static final String WORKER_ID = "WORKER_ID";
    private static final String DATA_CENTER_ID = "DATA_CENTER_ID";

    @Value("${spring.application.name}")
    private String appName;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 阿里云文件存储client
     * 只有配置了aliyun.oss.access-key才可以使用
     */
    @Bean
    @ConditionalOnClass(RedisUtils.class)
    public Sequence initSnowflakeIdWorker() {
        Integer workerId = 0;
        Integer dataCenterId = 0;
        Object o = redisUtils.hGet(IdRedisConstant.SNOWFLAKE_ID_APP + appName, WORKER_ID);
        Object o1 = redisUtils.hGet(IdRedisConstant.SNOWFLAKE_ID_APP + appName, DATA_CENTER_ID);
        if (null != o) {
            workerId = (Integer) o;
        }
        if (null != o1) {
            dataCenterId = (Integer) o1;
        }
        if (31 == workerId) {
            if (31 == dataCenterId) {
                workerId = 0;
                dataCenterId = 0;
            } else {
                dataCenterId += 1;
            }
        } else {
            if (31 == dataCenterId) {
                workerId += 1;
                dataCenterId = 0;
            } else {
                dataCenterId += 1;
            }
        }
        redisUtils.hSet(IdRedisConstant.SNOWFLAKE_ID_APP + appName, WORKER_ID, workerId);
        redisUtils.hSet(IdRedisConstant.SNOWFLAKE_ID_APP + appName, DATA_CENTER_ID, dataCenterId);
        Sequence idWorker = new Sequence(workerId.longValue(), dataCenterId.longValue());
        return idWorker;
    }

    @Bean
    @ConditionalOnMissingBean
    public DefaultRedisScript<Long> bidDefaultRedisScript() {
        DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/nextuuid.lua")));
        return defaultRedisScript;
    }
}
